package hashmap;

import java.lang.reflect.Method;
import java.util.*;

public class HashMapUtils {

    public static int getActualCapacityByInitCapacity(int initCapacity) throws Exception {
        Map<Integer, Integer> map;
        if (initCapacity >= 0) {
            map = new HashMap<>(initCapacity);
        } else {
            map = new HashMap<>();
        }
        Method capacity = map.getClass().getDeclaredMethod("capacity");
        capacity.setAccessible(true);
        int actualCapacity = (int) capacity.invoke(map);
        if (initCapacity >= 0) {
            System.out.println("入参容量为" + initCapacity + "时，实际容量为" + actualCapacity);
        } else {
            System.out.println("没有传入初始容量时，实际容量为" + actualCapacity);
        }
        return actualCapacity;
    }

    public static List<Integer> findRepeatedElements(int[] numArr, int repeatTimes) {
        Map<Integer, Integer> timeCounter = new HashMap<>(numArr.length);
        for (int num : numArr) {
            if (timeCounter.containsKey(num)) {
                Integer time = timeCounter.get(num);
                time++;
                timeCounter.put(num, time);
            } else {
                timeCounter.put(num, 1);
            }
        }
        Set<Integer> numSet = timeCounter.keySet();
        List<Integer> repeatedNum = new ArrayList<>();
        for (Integer num : numSet) {
            Integer time = timeCounter.get(num);
            if (time >= repeatTimes) {
                repeatedNum.add(num);
            }
        }
        return repeatedNum;
    }
}
